<template>
  <a-card class="employee-container">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="船舶编码" class="smart-query-form-item">
          <a-input v-model:value="params.targetId" placeholder="请输入船舶编码" />
        </a-form-item>
        <a-form-item label="船舶名称" class="smart-query-form-item">
          <a-input v-model:value="params.vesselName" placeholder="请输入船舶名称" />
        </a-form-item>
        <a-form-item label="起始时间" class="smart-query-form-item">
          <a-range-picker v-model:value="params.times" showTime />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="queryData">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="reset" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <div class="btn-group">
      <span class="smart-table-column-operate">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.SYSTEM.EMPLOYEE" :refresh="onload" />
      </span>
    </div>

    <a-table
      size="small"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      :loading="tableLoading"
      :scroll="{ y: 'calc(100vh - 350px)' }"
      row-key="employeeId"
      bordered
    >
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.dataIndex === 'img'">
          <a-image :width="80" :src="`${aiFileUrl}${record.imagesUrl}`" />
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button v-privilege="'system:employee:delete'" type="link" size="small" @click="handleDownload(record)">下载</a-button>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'vesselName'">
          <div class="smart-table-operate">
            {{ record.targetId ? shipList[record.targetId] || '未知船名' : '' }}
          </div>
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :defaultPageSize="params.size"
        v-model:current="params.current"
        v-model:pageSize="params.size"
        :total="total"
        @change="onload"
        @showSizeChange="onload"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>
</template>
<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { reactive, ref, onMounted } from 'vue';
  import { api } from '/@/api/plat/event-result';
  import { api as shipApi } from '/@/api/plat/ais-static.js';
  import { PAGE_SIZE } from '/@/constants/common-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import { dateFormat } from '/@/utils/date';

  const aiFileUrl = import.meta.env.VITE_APP_AIFILE;
  // ----------------------- 表格/列表/ 搜索 ---------------------
  //字段
  const columns = ref([
    {
      title: '摄像头名称',
      dataIndex: 'cameraName',
    },
    {
      title: '记录时间',
      dataIndex: 'resultTime',
    },
    {
      title: '船舶编号',
      dataIndex: 'targetId',
    },
    {
      title: '船舶名称',
      dataIndex: 'vesselName',
    },
    {
      title: '图片地址',
      dataIndex: 'imagesUrl',
    },
    {
      title: '在线预览',
      dataIndex: 'img',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'operate',
      width: 120,
    },
  ]);
  const tableData = ref();
  const shipList = ref({});

  let defaultParams = {
    current: 1,
    size: 10,
    targetId: undefined,
    vesselName: undefined,
    startTime: undefined,
    endTime: undefined,
    times: [],
  };
  const params = reactive({ ...defaultParams });
  const total = ref(0);

  // 搜索重置
  function reset() {
    Object.assign(params, defaultParams);
    onload();
  }

  function queryData() {
    params.current = 1;
    if (params.times && params.times.length > 0) {
      params.startTime = dateFormat(new Date(params.times[0]), 'yyyy-MM-dd hh:mm:ss');
      params.endTime = dateFormat(new Date(params.times[1]), 'yyyy-MM-dd hh:mm:ss');
    }
    onload();
  }

  const tableLoading = ref(false);
  // 查询
  async function onload() {
    tableLoading.value = true;
    try {
      let res = await api.queryArchivesPage(params);
      for (const item of res.data.records) {
        item.roleNameList = _.join(item.roleNameList, ',');
      }
      tableData.value = res.data.records;
      total.value = res.data.total;
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      tableLoading.value = false;
    }
  }

  function getShipList() {
    shipApi.queryList().then(({ data }) => {
      shipList.value = data.reduce((item, { mmsi, vesselName }) => {
        item[mmsi] = vesselName;
        return item;
      }, {});
      onload();
    });
  }

  onMounted(getShipList);

  function handleDownload(row) {
    let downloadFileUrl = `${aiFileUrl}${row.imagesUrl}`;
    const link = document.createElement('a');
    fetch(downloadFileUrl)
      .then((response) => response.blob())
      .then((blob) => {
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = row.imagesUrl.split('/').pop();
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url); // 清除对象URL，释放内存
      })
      .catch((error) => {
        console.error('下载图片失败:', error);
      });
  }
</script>
<style scoped lang="less">
  .employee-container {
    height: 100%;
  }
  .header {
    display: flex;
    align-items: center;
  }
  .query-operate {
    margin-left: auto;
    display: flex;
    align-items: center;
  }

  .btn-group {
    margin: 10px 0;
    .btn {
      margin-right: 8px;
    }
  }
</style>
